def topKFrequent( nums, k):
    from collections import defaultdict
    import heapq
    d = {}
    for i in nums:
        d[i] = d.get(i, 0) + 1
    heap = []
    n = 0
    m = 0
    for key, value in d.items():
        if (m < k):
            heapq.heappush(heap, (value, key))
            m += 1
        else:
            heapq.heappop(heap)
            heapq.heappush(heap, (value, key))
    # 最终剩余的元素就是前K个出现频率最高的元素
    # 不限制输出元素的排列顺序
    result = []
    print(len(heap))
    while (n < k):
        #####################
        # result.append(heapq.heappop(heap))
        # 一定要注意堆中存储的是一个元组:(频率,元素)
        #####################
        result.append(heapq.heappop(heap)[1])
        n += 1
    print(result)

if __name__ == '__main__':
    print(topKFrequent([1,1,1,2,2,3],2))